from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from django.shortcuts import get_object_or_404
from django.utils import timezone
from django.db.models import Q
from datetime import datetime, timedelta
from typing import Dict, Any

from portfolios.models import Portfolio
from portfolios.monitoring_models import (
    MonitoringRule, PortfolioMonitoring, Alert, QuarterlyReport,
    MarketIndicator, RebalanceRecommendation
)
from portfolios.monitoring_service import MonitoringService
from portfolios.serializers import PortfolioSerializer

@api_view(['POST'])
@permission_classes([IsAuthenticated])
def monitor_portfolio_allocation(request, portfolio_id):
    """监控投资组合配置偏离"""
    try:
        # 验证用户权限
        portfolio = get_object_or_404(Portfolio, id=portfolio_id, user=request.user)
        
        monitoring_service = MonitoringService()
        result = monitoring_service.monitor_portfolio_allocation(portfolio_id)
        
        if result['success']:
            return Response({
                'success': True,
                'message': '配置监控完成',
                'data': result
            }, status=status.HTTP_200_OK)
        else:
            return Response({
                'success': False,
                'message': result.get('error', '监控失败')
            }, status=status.HTTP_400_BAD_REQUEST)
            
    except Exception as e:
        return Response({
            'success': False,
            'message': f'监控配置偏离失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['POST'])
@permission_classes([IsAuthenticated])
def monitor_concentration_risk(request, portfolio_id):
    """监控集中度风险"""
    try:
        # 验证用户权限
        portfolio = get_object_or_404(Portfolio, id=portfolio_id, user=request.user)
        
        monitoring_service = MonitoringService()
        result = monitoring_service.monitor_concentration_risk(portfolio_id)
        
        if result['success']:
            return Response({
                'success': True,
                'message': '集中度风险监控完成',
                'data': result
            }, status=status.HTTP_200_OK)
        else:
            return Response({
                'success': False,
                'message': result.get('error', '监控失败')
            }, status=status.HTTP_400_BAD_REQUEST)
            
    except Exception as e:
        return Response({
            'success': False,
            'message': f'监控集中度风险失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['POST'])
@permission_classes([IsAuthenticated])
def monitor_performance_tracking(request, portfolio_id):
    """监控业绩跟踪"""
    try:
        # 验证用户权限
        portfolio = get_object_or_404(Portfolio, id=portfolio_id, user=request.user)
        
        monitoring_service = MonitoringService()
        result = monitoring_service.monitor_performance_tracking(portfolio_id)
        
        if result['success']:
            return Response({
                'success': True,
                'message': '业绩跟踪监控完成',
                'data': result
            }, status=status.HTTP_200_OK)
        else:
            return Response({
                'success': False,
                'message': result.get('error', '监控失败')
            }, status=status.HTTP_400_BAD_REQUEST)
            
    except Exception as e:
        return Response({
            'success': False,
            'message': f'监控业绩跟踪失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['POST'])
@permission_classes([IsAuthenticated])
def check_all_portfolios(request):
    """检查用户所有投资组合的监控条件"""
    try:
        monitoring_service = MonitoringService()
        result = monitoring_service.check_all_portfolios(user_id=request.user.id)
        
        if result['success']:
            return Response({
                'success': True,
                'message': '全部投资组合监控完成',
                'data': result['monitoring_results']
            }, status=status.HTTP_200_OK)
        else:
            return Response({
                'success': False,
                'message': result.get('error', '监控失败')
            }, status=status.HTTP_400_BAD_REQUEST)
            
    except Exception as e:
        return Response({
            'success': False,
            'message': f'检查所有投资组合失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_portfolio_alerts(request, portfolio_id):
    """获取投资组合预警"""
    try:
        # 验证用户权限
        portfolio = get_object_or_404(Portfolio, id=portfolio_id, user=request.user)
        
        # 获取查询参数
        alert_status = request.GET.get('status', 'active')
        alert_type = request.GET.get('type')
        alert_level = request.GET.get('level')
        
        # 构建查询条件
        filters = Q(portfolio=portfolio, status=alert_status)
        if alert_type:
            filters &= Q(alert_type=alert_type)
        if alert_level:
            filters &= Q(alert_level=alert_level)
        
        alerts = Alert.objects.filter(filters).order_by('-created_at')
        
        alert_list = []
        for alert in alerts:
            alert_data = {
                'id': alert.id,
                'alert_type': alert.alert_type,
                'alert_level': alert.alert_level,
                'title': alert.title,
                'message': alert.message,
                'alert_data': alert.alert_data,
                'status': alert.status,
                'created_at': alert.created_at.isoformat(),
                'acknowledged_at': alert.acknowledged_at.isoformat() if alert.acknowledged_at else None
            }
            alert_list.append(alert_data)
        
        return Response({
            'success': True,
            'message': '获取预警成功',
            'data': {
                'alerts': alert_list,
                'total_count': len(alert_list)
            }
        }, status=status.HTTP_200_OK)
        
    except Exception as e:
        return Response({
            'success': False,
            'message': f'获取预警失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['POST'])
@permission_classes([IsAuthenticated])
def acknowledge_alert(request, alert_id):
    """确认预警"""
    try:
        alert = get_object_or_404(Alert, id=alert_id, portfolio__user=request.user)
        
        if alert.status == 'acknowledged':
            return Response({
                'success': False,
                'message': '预警已经被确认'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        alert.status = 'acknowledged'
        alert.acknowledged_at = timezone.now()
        alert.acknowledged_by = request.user
        alert.save()
        
        return Response({
            'success': True,
            'message': '预警确认成功',
            'data': {
                'alert_id': alert.id,
                'acknowledged_at': alert.acknowledged_at.isoformat()
            }
        }, status=status.HTTP_200_OK)
        
    except Exception as e:
        return Response({
            'success': False,
            'message': f'确认预警失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['POST'])
@permission_classes([IsAuthenticated])
def generate_quarterly_report(request, portfolio_id):
    """生成季度报告"""
    try:
        # 验证用户权限
        portfolio = get_object_or_404(Portfolio, id=portfolio_id, user=request.user)
        
        # 获取季度参数
        quarter = request.data.get('quarter')  # 格式: 2024Q1
        
        monitoring_service = MonitoringService()
        result = monitoring_service.generate_quarterly_report(portfolio_id, quarter)
        
        if result['success']:
            return Response({
                'success': True,
                'message': '季度报告生成成功',
                'data': result
            }, status=status.HTTP_200_OK)
        else:
            return Response({
                'success': False,
                'message': result.get('error', '生成报告失败')
            }, status=status.HTTP_400_BAD_REQUEST)
            
    except Exception as e:
        return Response({
            'success': False,
            'message': f'生成季度报告失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_quarterly_reports(request, portfolio_id):
    """获取季度报告列表"""
    try:
        # 验证用户权限
        portfolio = get_object_or_404(Portfolio, id=portfolio_id, user=request.user)
        
        reports = QuarterlyReport.objects.filter(
            portfolio=portfolio
        ).order_by('-quarter')
        
        report_list = []
        for report in reports:
            report_data = {
                'id': report.id,
                'quarter': report.quarter,
                'title': report.title,
                'start_date': report.start_date.isoformat(),
                'end_date': report.end_date.isoformat(),
                'start_value': float(report.start_value),
                'end_value': float(report.end_value),
                'total_return': float(report.total_return),
                'benchmark_return': float(report.benchmark_return) if report.benchmark_return else None,
                'volatility': float(report.volatility) if report.volatility else None,
                'max_drawdown': float(report.max_drawdown) if report.max_drawdown else None,
                'sharpe_ratio': float(report.sharpe_ratio) if report.sharpe_ratio else None,
                'status': report.status,
                'created_at': report.created_at.isoformat()
            }
            report_list.append(report_data)
        
        return Response({
            'success': True,
            'message': '获取季度报告成功',
            'data': {
                'reports': report_list,
                'total_count': len(report_list)
            }
        }, status=status.HTTP_200_OK)
        
    except Exception as e:
        return Response({
            'success': False,
            'message': f'获取季度报告失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_quarterly_report_detail(request, report_id):
    """获取季度报告详情"""
    try:
        report = get_object_or_404(
            QuarterlyReport, 
            id=report_id, 
            portfolio__user=request.user
        )
        
        report_data = {
            'id': report.id,
            'portfolio_id': report.portfolio.id,
            'portfolio_name': report.portfolio.name,
            'quarter': report.quarter,
            'title': report.title,
            'start_date': report.start_date.isoformat(),
            'end_date': report.end_date.isoformat(),
            'start_value': float(report.start_value),
            'end_value': float(report.end_value),
            'total_return': float(report.total_return),
            'benchmark_return': float(report.benchmark_return) if report.benchmark_return else None,
            'volatility': float(report.volatility) if report.volatility else None,
            'max_drawdown': float(report.max_drawdown) if report.max_drawdown else None,
            'sharpe_ratio': float(report.sharpe_ratio) if report.sharpe_ratio else None,
            'allocation_analysis': report.allocation_analysis,
            'holdings_performance': report.holdings_performance,
            'recommendations': report.recommendations,
            'status': report.status,
            'created_at': report.created_at.isoformat()
        }
        
        return Response({
            'success': True,
            'message': '获取报告详情成功',
            'data': report_data
        }, status=status.HTTP_200_OK)
        
    except Exception as e:
        return Response({
            'success': False,
            'message': f'获取报告详情失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_monitoring_statistics(request):
    """获取监控统计信息"""
    try:
        user_portfolios = Portfolio.objects.filter(user=request.user)
        
        # 统计预警信息
        total_alerts = Alert.objects.filter(
            portfolio__in=user_portfolios,
            status='active'
        ).count()
        
        critical_alerts = Alert.objects.filter(
            portfolio__in=user_portfolios,
            status='active',
            alert_level='critical'
        ).count()
        
        warning_alerts = Alert.objects.filter(
            portfolio__in=user_portfolios,
            status='active',
            alert_level='warning'
        ).count()
        
        # 按类型统计预警
        alert_types = Alert.objects.filter(
            portfolio__in=user_portfolios,
            status='active'
        ).values('alert_type').distinct()
        
        type_statistics = {}
        for alert_type in alert_types:
            count = Alert.objects.filter(
                portfolio__in=user_portfolios,
                status='active',
                alert_type=alert_type['alert_type']
            ).count()
            type_statistics[alert_type['alert_type']] = count
        
        # 统计监控记录
        monitoring_records = PortfolioMonitoring.objects.filter(
            portfolio__in=user_portfolios
        ).count()
        
        triggered_records = PortfolioMonitoring.objects.filter(
            portfolio__in=user_portfolios,
            is_triggered=True
        ).count()
        
        # 统计季度报告
        quarterly_reports = QuarterlyReport.objects.filter(
            portfolio__in=user_portfolios
        ).count()
        
        statistics = {
            'alerts': {
                'total': total_alerts,
                'critical': critical_alerts,
                'warning': warning_alerts,
                'by_type': type_statistics
            },
            'monitoring': {
                'total_records': monitoring_records,
                'triggered_records': triggered_records,
                'trigger_rate': triggered_records / monitoring_records if monitoring_records > 0 else 0
            },
            'reports': {
                'quarterly_reports': quarterly_reports
            },
            'portfolios': {
                'total_portfolios': user_portfolios.count(),
                'active_portfolios': user_portfolios.filter(status='active').count()
            }
        }
        
        return Response({
            'success': True,
            'message': '获取监控统计成功',
            'data': statistics
        }, status=status.HTTP_200_OK)
        
    except Exception as e:
        return Response({
            'success': False,
            'message': f'获取监控统计失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['POST'])
@permission_classes([IsAuthenticated])
def create_monitoring_rule(request):
    """创建监控规则"""
    try:
        data = request.data
        
        rule = MonitoringRule.objects.create(
            name=data.get('name'),
            monitoring_type=data.get('monitoring_type'),
            threshold_value=data.get('threshold_value'),
            comparison_operator=data.get('comparison_operator', 'gt'),
            description=data.get('description', ''),
            is_active=data.get('is_active', True)
        )
        
        return Response({
            'success': True,
            'message': '监控规则创建成功',
            'data': {
                'rule_id': rule.id,
                'name': rule.name,
                'monitoring_type': rule.monitoring_type,
                'threshold_value': float(rule.threshold_value)
            }
        }, status=status.HTTP_201_CREATED)
        
    except Exception as e:
        return Response({
            'success': False,
            'message': f'创建监控规则失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_monitoring_rules(request):
    """获取监控规则列表"""
    try:
        rules = MonitoringRule.objects.filter(is_active=True).order_by('monitoring_type')
        
        rule_list = []
        for rule in rules:
            rule_data = {
                'id': rule.id,
                'name': rule.name,
                'monitoring_type': rule.monitoring_type,
                'threshold_value': float(rule.threshold_value),
                'comparison_operator': rule.comparison_operator,
                'description': rule.description,
                'is_active': rule.is_active,
                'created_at': rule.created_at.isoformat()
            }
            rule_list.append(rule_data)
        
        return Response({
            'success': True,
            'message': '获取监控规则成功',
            'data': {
                'rules': rule_list,
                'total_count': len(rule_list)
            }
        }, status=status.HTTP_200_OK)
        
    except Exception as e:
        return Response({
            'success': False,
            'message': f'获取监控规则失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)